<?php


namespace app\admin\controller;

use app\common\model\AdminModel;
use app\common\model\LinksModel;
use think\facade\Cookie;
use think\facade\Request;

class LinksController extends BaseController {
    public function index() {
        return $this->fetch();
    }

    public function add() {
        return $this->fetch();
    }

    public function edit() {
        $links = LinksModel::where(['id' => Request::param('id')])->find();
        $this->assign('links', $links);
        return $this->fetch();
    }

    public function getList() {
        $page  = Request::param("page");
        $limit = Request::param("limit");
        $links = LinksModel::order("sort desc")->limit(($page - 1) * $limit, $limit)->select();
        $count = LinksModel::count("id");
        if ($count > 0) {
            return json(["code" => 0, "msg" => "", "data" => $links, "count" => $count]);
        }
        return self::bulidFail('暂无数据');
    }

    public function add_post() {
        $params             = Request::param();
        $links              = new LinksModel($params);
        $links->create_time = date("Y-m-d H:i:s");
        if ($links->save()) {
            // 记录日志
            $log_content = "添加友情链接，ID：{$links->id}，标题：{$links->title}，链接：{$links->url}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess([], '添加成功');
        }
        return self::bulidFail();
    }

    public function edit_post() {
        $links = LinksModel::where(['id' => Request::param('id')])->find();
        if (!$links) {
            return self::bulidFail('数据异常');
        }
        $links->title       = Request::param('title');
        $links->url         = Request::param('url');
        $links->update_time = date("Y-m-d H:i:s");
        if ($links->save()) {
            // 记录日志
            $log_content = "编辑友情链接，ID：{$links->id}，标题：{$links->title}，链接：{$links->url}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }

    public function del_post() {
        $id    = Request::param('id');
        $links = LinksModel::get($id);
        if (!$links) {
            return self::bulidFail('未查询到相关活动');
        }

        if (LinksModel::where(['id' => $id])->delete()) {
            // 记录日志
            $log_content = "删除友情链接，ID：{$links->id}，标题：{$links->title}，链接：{$links->url}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }
}
